import { useStore } from '@/hooks';
import { Button, Dialog, Form, Message } from '@alifd/next';
import TauTable from '@/components/TauTable';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { FieldsGrid, TitleGrid, column, model } from '../stores/definitions';
import { observer } from 'mobx-react-lite';
import { observable, toJS } from 'mobx';
import ChargeForm from './ChargeForm';

const FromItem = Form.Item;

const rules = model.priceRules;

const DataForm = ({ id, onCancel, modal, onSubmit, ...formProps }) => {
  const { driverGroupStore: store } = useStore();
  const { show, record, toClose } = modal;
  console.log(modal);

  const [driver] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [isViewMode] = useState(show === 'view');
  const [state, setState] = useState([]);
  const [stateMOP, setStateMOP] = useState([]);
  const [curCharge, setCurCharge] = useState();
  const [idx, setIdx] = useState(0);
  const [idxMOP, setIdxMOP] = useState(0);

  useEffect(() => {
    if (toClose?.startsWith?.('toClose')) handleCancel();
  }, [modal]);

  useEffect(() => {
    (async () => {
      if (id) {
        const res = await store.getId(id);
        const { priceRules } = res;
        setState(priceRules.filter((p) => p.priceType == 0).sort((a, b) => a.startPrice - b.startPrice));
        setStateMOP(priceRules.filter((p) => p.priceType == 1).sort((a, b) => a.startPrice - b.startPrice));
        editCtx.origin = _.cloneDeep(res);
        _.assign(driver, res);
      } else {
        _.set(driver, 'noticeRules', []);
      }
    })();
  }, []);

  const overrideModel = {
    priceRules: {
      ui: {
        renderer: () => {
          return (
            <>
              {!isViewMode && <Button type="primary" onClick={() => handleAddRule(0)}>{t`添加普通线路规则`}</Button>}
              <TitleGrid title={t`普通线路规则`} />
              <TauTable
                hidePagination
                dataSource={state}
                onRowClick={(_, index) => setIdx(index)}
                columns={[
                  { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
                  column('startPrice', {}, rules),
                  column('endPrice', {}, rules),
                  column('issueOrderPoint', {}, rules),
                  column('takeOrderPoint', {}, rules),
                  column('remarks', {}, rules),
                  {
                    title: t`操作`,
                    dataIndex: 'refundNumber',
                    width: 180,
                    cell: (_, i, r) => (
                      <>
                        <Button key={'1'} text type="primary" onClick={() => handleEdit(r)}>{t`编辑`}</Button>
                        <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                        <Button
                          key={'2'}
                          text
                          style={{ color: 'red' }}
                          type="normal"
                          onClick={() => handleRemove(i, 0)}
                        >{t`删除`}</Button>
                      </>
                    ),
                  },
                ]}
              />
              <TitleGrid title={t`澳门线路规则`} />
              {!isViewMode && <Button type="primary" onClick={() => handleAddRule(1)}>{t`添加澳门线路规则`}</Button>}
              <TauTable
                hidePagination
                dataSource={stateMOP}
                onRowClick={(_, index) => setIdxMOP(index)}
                columns={[
                  { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
                  column('startPrice', {}, rules),
                  column('endPrice', {}, rules),
                  column('issueOrderPoint', {}, rules),
                  column('takeOrderPoint', {}, rules),
                  column('remarks', {}, rules),
                  {
                    title: t`操作`,
                    dataIndex: 'refundNumber',
                    width: 180,
                    cell: (_, i, r) => (
                      <>
                        <Button key={'1'} text type="primary" onClick={() => handleEdit(r)}>{t`编辑`}</Button>
                        <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                        <Button
                          key={'2'}
                          text
                          style={{ color: 'red' }}
                          type="normal"
                          onClick={() => handleRemove(i, 1)}
                        >{t`删除`}</Button>
                      </>
                    ),
                  },
                ]}
              />
            </>
          );
        },
        span: 4,
      },
    },
  };

  const handleAddRule = (type) => {
    const isTypeZero = type === 0;
    const setList = isTypeZero ? setState : setStateMOP;
    const priceType = isTypeZero ? 0 : 1;

    setList((prev) => {
      const data = [...prev];
      setIdx(isTypeZero ? data.length : undefined);
      setIdxMOP(isTypeZero ? undefined : data.length);
      setCurCharge({ priceType });
      return data;
    });
  };

  const handleEdit = (r) => {
    setCurCharge(r);
  };

  const handleRemove = (index, listType) => {
    const setList = listType === 0 ? setState : setStateMOP;

    setList((prev) => {
      const updatedArray = prev.filter((_, i) => i !== index);
      return updatedArray;
    });
  };

  const chargeOnSubmit = (values, errors) => {
    if (errors) {
      return;
    }
    const { priceType } = values;
    const tempState = values?.priceType == 0 ? state : stateMOP;
    const tempIdx = values?.priceType == 0 ? idx : idxMOP;
    const _type = store.uniqueState(values, tempState, curCharge, tempIdx);
    if (_type) {
      Message.error({ content: store._MESSAGE_TEXT[_type], duration: 7000 });
      return;
    }
    // 如果没有重复或交集，添加新数据到数组中
    if (priceType == 0) {
      const tempData = _.cloneDeep(state);
      tempData[idx] = values;
      tempData.sort((a, b) => a.startPrice - b.startPrice);
      setState(tempData);
    } else {
      const tempData = _.cloneDeep(stateMOP);
      tempData[idxMOP] = values;
      tempData.sort((a, b) => a.startPrice - b.startPrice);
      setStateMOP(tempData);
    }
    setCurCharge(false);
  };

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(driver, name, value);
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: ActivityForm.jsx:213 _ errors:', errors);
      return;
    }
    console.log(toJS(driver), 'priceRules', [...state, ...stateMOP]);
    // _.set(driver, 'priceRules', [...state, ...stateMOP]);
    // onSubmit?.(driver);
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form {...formProps} value={driver} onChange={handleChange} inline useLabelForErrorMessage>
      <TitleGrid title={t`基本信息`} />
      <FieldsGrid
        formData={driver}
        mode={show}
        columns={4}
        overrideModel={overrideModel}
        fields={[
          'groupName',
          'enable',
          'managerName',
          'managerPhone',
          'accountingName',
          'accountingPhone',
          'urgentOrderRule',
          'takeOrderInterval',
          'reserveOrderInterval',
          'urgentOrderInterval',
          'description',
        ]}
      />
      <FieldsGrid formData={driver} mode={show} columns={4} overrideModel={overrideModel} fields={['priceRules']} />
      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
      <Dialog
        visible={!!curCharge}
        onCancel={() => setCurCharge(false)}
        onClose={() => setCurCharge(false)}
        title={t`编辑内容`}
        style={{ width: '30%' }}
        footer={null}
      >
        <ChargeForm
          data={curCharge}
          onSubmit={(r, errors) => chargeOnSubmit(r, errors)}
          onCancel={() => setCurCharge(false)}
        />
      </Dialog>
    </Form>
  );
};

export default observer(DataForm);
